//
//  HRFollowDynamicCell.m
//  Hear
//
//  Created by mac on 2017/5/19.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRFollowDynamicCell.h"
#import "HRFollowDynamicPhotoView.h"
#import "HRDynamicInfoHeadView.h"
#import "HRCoverImageModel.h"
#import "HRCoverTimeModel.h"
#import "NSMutableAttributedString+GDAttString.h"
#import "HRDynamicCommentView.h"
#import "YBPopupMenu.h"
#import "HRUMShareTool.h"
#import "HRArtPlayerView.h"
#import "HRDynamicSoundAndImageBackGroundView.h"
#import "UIButton+SSEdgeInsets.h"
#import "WBTextLinePositionModifier.h"
#import "HRNoviceBootViewController.h"
@interface HRFollowDynamicCell ()<YBPopupMenuDelegate>
@property (nonatomic, strong)UIView *contView;

@property (nonatomic, strong)UIImageView *iconImageView;
@property (nonatomic, strong)UILabel *nickNameLabel;
@property (nonatomic, strong)UILabel *timeLabel;
@property (nonatomic, strong)HRFollowDynamicPhotoView *dynamicPhotoView;
@property (nonatomic, strong)UILabel *contentLabel;
@property (nonatomic, strong)HRSoundButton *soundButton;
@property (nonatomic, strong)HRDynamicToolView *dynamicToolView;
@property (nonatomic, strong)HRDynamicCommentView *commentView;
@property (nonatomic, strong)UIButton *moreButton;
@property(nonatomic, strong)UIButton *showMoreContentButton;

//@property (nonatomic, strong)HRArtPlayerView *playerView;
@property(nonatomic, strong)UIButton *tagButton;
@property(nonatomic, strong)HRDynamicSoundAndImageBackGroundView *soundAndImageView;

@end
@implementation HRFollowDynamicCell

- (void)updataFrame{
    self.contView.frame = _layout.contViewFrame;
    self.iconImageView.frame = _layout.iconImageViewFrame;
    self.nickNameLabel.frame = _layout.nickNameLabelFrame;
    self.timeLabel.frame = _layout.timeLabelFrame;
    
    self.moreButton.frame = _layout.moreButtonFrame;
    
    self.dynamicPhotoView.frame = _layout.dynamicPhotoViewFrame;
    self.contentLabel.frame = _layout.contentLabelFrame;
    
    self.showMoreContentButton.frame = _layout.showMoreContentButtonFrame;
    
    self.soundButton.frame = _layout.soundButtonFrame;
    
    self.commentView.frame = _layout.commentViewFrame;
    
    //    self.playerView.frame = layout.playerViewFrame;
    
    self.dynamicToolView.frame = _layout.dynamicToolViewFrame;
    
    self.tagButton.frame = _layout.tagButtonFrame;
    
    self.soundAndImageView.frame = _layout.soundAndImageViewFrame;
}


-(void)setLayout:(HRFollowDynamicLayout *)layout{
    
    _layout = layout;
    WeakSelf
    [self updataFrame];
    
    HRDynamicModel *dynamicModel = layout.dynamicModel;
    

    
    if ([dynamicModel.UserPictureBackgroundColor length]){
        [HRCoverImageModel OriginImage:[UIImage imageNamed:dynamicModel.UserPictureName] scaleToSize:CGSizeMake(75, 75) callBackOriginImage:^(UIImage *originImage) {
            weakSelf.iconImageView.image = originImage;
        }];
        self.iconImageView.backgroundColor = [UIColor colorWithHexString:dynamicModel.UserPictureBackgroundColor];
    }else{
        [self.iconImageView setImageWithURL:[NSURL URLWithString:dynamicModel.UserPictureName] placeholder:[UIImage imageNamed:@""]];
    }
    
    self.nickNameLabel.text = dynamicModel.UserRemark.length>0?dynamicModel.UserRemark:dynamicModel.NickName;
    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *timeText = [HRCoverTimeModel covetTime:dynamicModel.CreateTime];
        dispatch_async(dispatch_get_main_queue(), ^{
           self.timeLabel.text = timeText;
        });
    });
    
    
//    [self getContentText];
    self.contentLabel.attributedText = [NSMutableAttributedString attStringFromTextForChatting:_layout.dynamicModel.MomentNotes textFont:CustomUIFont(14)];

    
    self.commentView.dynamicModel = dynamicModel;
    
    self.dynamicToolView.dynamicModel = dynamicModel;
    
    
    
//    self.playerView.videoUrl = [NSURL URLWithString:dynamicModel.MomentDetai];
//    [self.playerView loadNetworkVideo];
    
    [self.tagButton setTitle:[NSString stringWithFormat:@" %@",dynamicModel.MomentTagName] forState:0];

    
    if ([dynamicModel.MomentType intValue] == 1){
        self.soundButton.dynamicModel = dynamicModel;
        self.dynamicPhotoView.hidden = YES;
        self.soundAndImageView.hidden = YES;
    }else if ([dynamicModel.MomentType intValue] == 2){
        self.dynamicPhotoView.picArr = dynamicModel.pics;
        self.soundAndImageView.hidden = YES;
        self.dynamicPhotoView.hidden = NO;
        self.soundButton.hidden = YES;
    }else if ([dynamicModel.MomentType intValue] == 3){
        self.dynamicPhotoView.hidden = YES;
        self.soundAndImageView.hidden = YES;
        self.soundButton.hidden = YES;
    }else if ([dynamicModel.MomentType intValue] == 4){
        self.dynamicPhotoView.hidden = YES;
        self.soundAndImageView.hidden = YES;
        self.soundButton.hidden = YES;
    }else if ([dynamicModel.MomentType intValue] == 5){
        self.soundAndImageView.dynamicModel = layout.dynamicModel;
        self.soundAndImageView.hidden = NO;
        self.dynamicPhotoView.hidden = YES;
        self.soundButton.hidden = YES;
    }
    
    
    if(layout.isShowRealyCellHeight){
        [self.showMoreContentButton setTitle:@"收起" forState:0];
        [self.contentLabel sizeToFit];
    }else{
        [self.showMoreContentButton setTitle:@"展开" forState:0];

    }
    
    if ([dynamicModel.IsRecommend intValue] ==1){
        [self.moreButton setTitle:@"推荐" forState:0];
        self.moreButton.width = 50;
        self.moreButton.left = kFullWidth-self.moreButton.width-10;
        [self.moreButton setImagePositionWithType:SSImagePositionTypeRight spacing:4];
    }else{
        [self.moreButton setTitle:@"" forState:0];
        self.moreButton.width = 20;
        self.moreButton.left = kFullWidth-self.moreButton.width-10;
    }

    if (dynamicModel.isFromHistoryAnswer){
        self.moreButton.hidden = YES;
        self.tagButton.hidden = YES;
    }
}


- (void)getContentText{
//    self.contentLabel.attributedText = [NSMutableAttributedString attStringFromTextForChatting:_layout.dynamicModel.MomentNotes textFont:CustomUIFont(14)];

    if(!_layout.dynamicModel.MomentNotes.length){
        _layout.dynamicModel.MomentNotes = @"";
    }
    
//    NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:_layout.dynamicModel.MomentNotes];
    NSMutableParagraphStyle * paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:8];
    
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSError *error;

    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:_layout.dynamicModel.MomentNotes options:0 range:NSMakeRange(0, [_layout.dynamicModel.MomentNotes length])];
    NSMutableArray *arr=[[NSMutableArray alloc]init];
    NSMutableArray *rangeArr=[[NSMutableArray alloc]init];
    
    for (NSTextCheckingResult *match in arrayOfAllMatches)
    {
        NSString* substringForMatch;
        substringForMatch = [_layout.dynamicModel.MomentNotes substringWithRange:match.range];
        [arr addObject:substringForMatch];
        
    }
    NSString *subStr= _layout.dynamicModel.MomentNotes;
    
    UIFont *font = [UIFont systemFontOfSize:20];
    NSMutableAttributedString *attributedText;
    attributedText = [self _textWithStatus:NO
                                   fontSize:14
                                  textColor:UIColorHex(333333)];

    WBTextLinePositionModifier *modifier = [WBTextLinePositionModifier new];
    modifier.font = CustomUIFont(14);
    modifier.paddingTop = 10;
    modifier.paddingBottom = 10;
    
    YYTextContainer *container = [YYTextContainer new];
    container.truncationType = YYTextTruncationTypeStart;
    container.size = CGSizeMake(self.contentLabel.width, HUGE);
    container.linePositionModifier = modifier;
//    self.contentLabel.textLayout = [YYTextLayout layoutWithContainer:container text:attributedText];
    
}
- (NSMutableAttributedString *)_textWithStatus:(BOOL)isRetweet
                                      fontSize:(CGFloat)fontSize
                                     textColor:(UIColor *)textColor{
    if (!_layout.dynamicModel.MomentNotes.length) return nil;
    NSMutableString *string = _layout.dynamicModel.MomentNotes;
    if (string.length == 0) return nil;
    UIFont *font = [UIFont systemFontOfSize:fontSize];
    // 高亮状态的背景
    YYTextBorder *highlightBorder = [YYTextBorder new];
    highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
    highlightBorder.cornerRadius = 3;
    highlightBorder.fillColor = UIColorHex(bfdffe);
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:string];
    text.font = font;
    text.color = textColor;
    
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    NSError *error;
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];

    
    for (NSTextCheckingResult *at in arrayOfAllMatches) {
        if (at.range.location == NSNotFound && at.range.length <= 1) continue;
        if ([text attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil) {
            [text setColor:UIColorHex(527ead) range:at.range];
            
            // 高亮状态
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setBackgroundBorder:highlightBorder];
            // 数据信息，用于稍后用户点击
            highlight.userInfo = @{@"http" : [text.string substringWithRange:NSMakeRange(at.range.location + 1, at.range.length - 1)]};
            [text setTextHighlight:highlight range:at.range];
        }
    }
    return text;
    
}

//获取查找字符串在母串中的NSRange
- (NSValue *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
    
    NSRange searchRange = NSMakeRange(0, [str length]);
    
    NSRange range;
    
    if ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
        searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
    }
    return [NSValue valueWithRange:range];
}


+(instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *cellID = @"HRFollowDynamicCell";
    
    HRFollowDynamicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if(!cell){
        cell = [[HRFollowDynamicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    return cell;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self)
    {
        WeakSelf
        self.backgroundColor = CustomColor(240, 240, 240, 1);
        
        
        UIView *contView = [UIView new];
        [self addSubview:(self.contView = contView)];
        contView.backgroundColor = [UIColor whiteColor];
        
        UIImageView *iconImageView = [UIImageView new];
        iconImageView.contentMode = UIViewContentModeScaleAspectFill;
        iconImageView.clipsToBounds = YES;
        iconImageView.layer.cornerRadius = 25;
        [contView addSubview:(self.iconImageView = iconImageView)];
        iconImageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *iconTap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
            if (weakSelf.clickIconBlock){
                weakSelf.clickIconBlock();
            }
        }];
        [iconImageView addGestureRecognizer:iconTap];
        
        self.nickNameLabel = [UILabel new];
        self.nickNameLabel.textColor = CustomColor(28, 190, 160, 1);
        self.nickNameLabel.font = CustomUIFont(16);
        [contView addSubview:self.nickNameLabel];
        
        
        self.timeLabel = [UILabel new];
        
        self.timeLabel.font = CustomUIFont(12);
        self.timeLabel.textColor = CustomColor(144, 144, 144, 1);
        [contView addSubview:self.timeLabel];
        
        
        self.moreButton = [UIButton buttonWithType:0];
        [self.moreButton setTitleColor:FirstTextColor forState:0];
        [self.moreButton setImage:[UIImage imageNamed:@"更多"] forState:UIControlStateNormal];
        self.moreButton.titleLabel.font = CustomUIFont(13);
        [self.moreButton addTarget:self action:@selector(moreButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [contView addSubview:self.moreButton];
        
        
        self.contentLabel = [UILabel new];
        self.contentLabel.textColor = CustomColor(66, 66, 66, 1);
        self.contentLabel.font = CustomUIFont(14);
        [contView addSubview:self.contentLabel];
        self.contentLabel.numberOfLines = 0;
        self.contentLabel.userInteractionEnabled = YES;
//        self.contentLabel.displaysAsynchronously = YES;
//        self.contentLabel.ignoreCommonProperties = YES;
//        self.contentLabel.fadeOnAsynchronouslyDisplay = NO;
//        self.contentLabel.fadeOnHighlight = NO;
        [self.contentLabel addGestureRecognizer: [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longTap:)]];
//        self.contentLabel.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
////            DDLog(@"");
//            NSString *url = [_layout.dynamicModel.MomentNotes substringWithRange:range];
//            HRNoviceBootViewController *rootVC = [HRNoviceBootViewController new];
////            rootVC.title = @"新手引导";
//            rootVC.requestUrl = url;
//            [VIEWCCONTROLER.navigationController pushViewController:rootVC animated:YES];
//        };
        
        self.dynamicPhotoView = [HRFollowDynamicPhotoView new];
        [contView addSubview:self.dynamicPhotoView];
        
        self.soundAndImageView = [HRDynamicSoundAndImageBackGroundView new];
        [contView addSubview:self.soundAndImageView];
        self.soundAndImageView.playMedioBlock = ^(HRDynamicModel *currentDynamicModel){
            if (weakSelf.playMedioBlock){
                weakSelf.playMedioBlock(currentDynamicModel);
            }
        };
        
        
        
        _soundButton = [HRSoundButton buttonWithType:0];
        [contView addSubview:_soundButton];
        _soundButton.playMedioBlock = ^(HRDynamicModel *currentDynamicModel){
            if (weakSelf.playMedioBlock){
                weakSelf.playMedioBlock(currentDynamicModel);
            }
        };
        
        
        
        self.showMoreContentButton = [UIButton buttonWithType:0];
        [self.showMoreContentButton setTitle:@"展开" forState:0];
        [self.showMoreContentButton setTitleColor:MainColor forState:0];
        self.showMoreContentButton.titleLabel.font = CustomUIFont(13);
        [self.showMoreContentButton addTarget:self action:@selector(showMoreContentButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [contView addSubview:self.showMoreContentButton];
        
        
//        self.playerView = [HRArtPlayerView new];
//        [contView addSubview:self.playerView];
//
        self.tagButton = [UIButton buttonWithType:0];
        [self.tagButton setImage:[UIImage imageNamed:@"标签icon-拷贝"] forState:0];
        [self.tagButton setTitleColor:MainColor forState:0];
        self.tagButton.titleLabel.font = CustomUIFont(12);
        [self.tagButton addTarget:self action:@selector(tagButtonSender) forControlEvents:UIControlEventTouchUpInside];
        [contView addSubview:self.tagButton];
        
        
        
        HRDynamicCommentView *commentView = [HRDynamicCommentView new];
        [contView addSubview:(self.commentView = commentView)];
        
        HRDynamicToolView *dynamicToolView = [HRDynamicToolView new];
        [self addSubview:(self.dynamicToolView = dynamicToolView)];
        dynamicToolView.backgroundColor = [UIColor whiteColor];
        dynamicToolView.likeButtonClickBlock = ^(BOOL isLike){
            if (weakSelf.likeButtonClickBlock){
                weakSelf.likeButtonClickBlock(isLike);
            };
        };
        
        
        
    }
    return self;
}


#pragma -mark- 展开
- (void)showMoreContentButtonClick{
    if (self.showMoreContentButtonBlock){
        self.showMoreContentButtonBlock();
    }
}


- (void)tagButtonSender{
    if (self.tagButtonSenderBlock){
        self.tagButtonSenderBlock();
    }
}


- (void)moreButtonClick{
    [YBPopupMenu showRelyOnView:self.moreButton titles:@[@"转发"] icons:nil menuWidth:100.f textColor:MainColor delegate:self];
}

#pragma -mark- YBPopupMenuDelegate
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu{
    if(index == 0){
        NSString *contentStr = @"";
        if (self.layout.dynamicModel.MomentNotes.length){
            contentStr = self.layout.dynamicModel.MomentNotes;
        }else{
            contentStr = @"我在Hear留下的瞬间";
        }
        
        
        [HRUMShareTool uMShareToolTitle:contentStr andContentStr:contentStr andImage:[UIImage imageNamed:@"hearicon"] andShareUrl:[NSString stringWithFormat:@"%@/M/MomentShare/%@",ShareHeadUrl,self.layout.dynamicModel.LocalId]isSeccess:^(BOOL isSeccess) {
            
        }];
    }else{
        
    }
}
- (void)ybPopupMenuBeganShow{
    self.moreButton.imageView.transform = CGAffineTransformRotate(self.contView.transform, M_PI);
}

- (void)ybPopupMenuBeganDismiss{
    self.moreButton.imageView.transform = CGAffineTransformIdentity;
}


- (void)longTap:(UILongPressGestureRecognizer *)longRecognizer
{
    //判断 如果当前是长按状态
    if (longRecognizer.state==UIGestureRecognizerStateBegan)
    {
        [self becomeFirstResponder];
        //创建一个菜单控制器  单例
        UIMenuController *menu=[UIMenuController sharedMenuController];
        //        //创建两个菜单按钮
        //        UIMenuItem *copyItem = [[UIMenuItem alloc] initWithTitle:@"删除" action:@selector(copyItemClicked:)];
        
        UIMenuItem *resendItem = [[UIMenuItem alloc] initWithTitle:@"复制" action:@selector(copyItemClicked:)];
        //添加到控制器上
        [menu setMenuItems:[NSArray arrayWithObjects:resendItem,nil]];
        //菜单的位置  在cell 的边界
        CGRect rect = CGRectMake(self.contentLabel.centerX, self.contentLabel.top,50, 1);
        [menu setTargetRect:rect inView:self];
        //菜单的显示
        [menu setMenuVisible:YES animated:YES];
    }
}

-(BOOL)canBecomeFirstResponder{
    
    return YES;
    
}
// 用于UIMenuController显示，缺一不可
-(BOOL)canPerformAction:(SEL)action withSender:(id)sender{
    
    if (action ==@selector(copyItemClicked:)){
        
        return YES;
        
    }
    
    return NO;//隐藏系统默认的菜单项
}

-(void)copyItemClicked:(id)sender{
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (_layout.dynamicModel.MomentNotes.length != 0)
    {
        [pasteboard setString:_layout.dynamicModel.MomentNotes];
    }
    
    
}




- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
